#!/usr/local/bin/python
# -*- coding: utf-8 -*-

import socket 
from settings import server
from settings import channel
from settings import botnick
from settings import identify

log = []

def ping(): # This is respond to server Pings.
    ircsock.send("PONG :pingis\n")  

def joinchan(chan):
    ircsock.send("JOIN "+ chan +"\n")

def sendmsg(chan, msg):
    ircsock.send("NOTICE "+ chan +" :"+ msg +"\n")
    
def get_user(msg):
    user = ircmsg.split(":")[1].split("!")[0]
    return user
    
def log_write(str):
    if str.find(" PRIVMSG "+channel) != -1:
        logmsg = str[1:str.find("!")] + str.split("PRIVMSG "+channel+" ")[1]
        log.append(logmsg)
    
def onHelp(user):
    helpmsg = ["Команди:",
     "    !v nickname - дає voice",
     "    !dv nickname - забирає voice",
     "    !log - останні 20 повідомлень",
     "    ",
     "    !about - інформація про бота \n"]
    for msg in helpmsg:
        sendmsg(user, msg)
    
def onAbout(user):
    aboutmsg = ["pyboty 0.01",
    "    pyboty IRC bot",
    "    http://code.google.com/p/pyboty \n"]
    for msg in aboutmsg:
        sendmsg(user, msg)

def mode_voice(user):
    ircsock.send("MODE "+channel+" +v "+user+"\n")
    
def mode_devoice(user):
    ircsock.send("MODE "+channel+" -v "+user+"\n")

ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ircsock.connect((server, 6667))
ircsock.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :I'm pyboty!\n")
ircsock.send("NICK "+ botnick +"\n")
ircsock.send("PRIVMSG NICKSERV :IDENTIFY "+ identify +"\n")

joinchan(channel)
ircsock.send("PRIVMSG "+channel+" :Всім привіт!)\n")

while 1:
    ircmsg = ircsock.recv(2048) 
    ircmsg = ircmsg.strip('\n\r') 
    print(ircmsg) # Print what's coming from the server
    
    if ircmsg.find(".freenode.net") == -1:
        log_write(ircmsg)

    if ircmsg.find("KICK "+channel+" "+botnick) != -1:
        joinchan(channel)

    if ircmsg.find (":!"+botnick) != -1:
        ircsock.send("PRIVMSG "+channel+" :    (^_^)\n")
        
    if ircmsg.find (":!v ") != -1:
        user = ircmsg.split(":!v ")[-1]
        mode_voice(user)
    if ircmsg.find (":!dv ") != -1:
        user = ircmsg.split(":!dv ")[-1]
        mode_devoice(user)
        
    if ircmsg.find (":!log") != -1:
        user = get_user(ircmsg)
        for msg in log:
            sendmsg(user, msg)
    
    if ircmsg.find(":!help") != -1:
        user = get_user(ircmsg)
        onHelp(user)
    if ircmsg.find(":!about") != -1:
        user = get_user(ircmsg)
        onAbout(user)

    ## PING
    if ircmsg.find("PING :") != -1:
        ping()
